<script lang="ts" setup>
import { useBeforeDate } from 'co-utils-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { computed, createVNode, PropType, render } from 'vue';

import { deleteCommentItem, postArticleComment } from '@/api/comment';
import { ICommentList } from '@/api/comment/type';

import Comment from './Comment.vue';
import { useEmojiTransform } from './index';
import SubReply from './SubReply.vue';

defineOptions({
  name: 'Reply'
});
const props = defineProps({
  data: {
    type: Object as PropType<ICommentList.IResponse>,
    default: () => {
    }
  }
});
const emits = defineEmits(['sub-reply-success']);
const commentRef = ref<HTMLDivElement | null>(null);
const subCommentRefs = ref<(HTMLDivElement | null)[]>([]);
const dataComputed = computed(() => props.data?.list);
const commentContent = ref('');

/**
 * 删除节点
 */
const handleElementRemove = () => {
  const commentItem = commentRef.value?.querySelectorAll('.comment-item,.sub-comment-item');
  if (!commentItem) return;
  // 过滤只包含reply-comment的父节点
  const _commentItemDom = Array.from(commentItem).filter(item => item.querySelector('.reply-comment'));
  _commentItemDom?.forEach(VNodeItem => {
    const _comment = VNodeItem.querySelector('.reply-comment');
    if (_comment && VNodeItem.contains(_comment)) {
      _comment.remove();
    }
  });
};
const handleGetCommentList = () => {
  emits('sub-reply-success');
  handleElementRemove();
};
/**
 * 提交二级评论
 */
const handleSubMit = async (item: ICommentList.SubCommentList, type: 1 | 2) => {
  if (!commentContent.value) {
    ElMessage.error('评论内容不能为空');
    return;
  }
  await postArticleComment({
    blogUid: item.blogUid,
    content: commentContent.value,
    replyId: type === 2 ? item.subCommentId : undefined,
    parentId: type === 2 ? item.parentId : item.commentId
  });
  commentContent.value = '';
  handleGetCommentList();
};
const createCommentVNode = (item: ICommentList.SubCommentList, type: 1 | 2) => {
  const vm = createVNode(Comment, {
    onOnSubMit: (v: string) => {
      commentContent.value = v;
      handleSubMit(item, type);
    },
    placeholder: `回复 ${item.userInfo.username}`
    // 'onUpdate:value': (v: string) => {
    //   // commentContent.value = v;
    // }
  });
  // 创建父级包裹对象
  const container = document.createElement('div');
  // 设置样式宽度和高度为100%
  container.style.width = '100%';
  container.style.height = '100%';
  container.className = 'reply-comment';
  render(vm, container);
  return container;
};
const handleClickComment = (
  _VNode: HTMLDivElement,
  index: number,
  _type: 1 | 2,
  _commentItem: ICommentList.SubCommentList
) => {
  // 查询是否已经存在回复评论节点，存在，则删除
  if (_type === 1) {
    const commentVNode = _VNode?.children[index].querySelector('.sub-comment-item .reply-comment');
    if (commentVNode) {
      commentVNode.remove();
      _VNode?.children[index]
        .querySelector('.content-box .comment-main .action-box')
        ?.insertAdjacentElement('afterend', createCommentVNode(_commentItem, _type));
    } else {
      const commentNode = _VNode?.children[index].querySelector('.reply-comment');
      if (!commentNode) {
        _VNode?.children[index]
          .querySelector('.content-box .comment-main .action-box')
          ?.insertAdjacentElement('afterend', createCommentVNode(_commentItem, _type));
      } else {
        commentNode.remove();
      }
    }
    return;
  }
  const commentVNode = _VNode?.children[index].querySelector('.reply-comment');
  console.log(commentVNode);
  if (commentVNode) {
    _VNode.children[index].querySelector('.comment-main')?.removeChild(commentVNode);
  } else {
    handleElementRemove();
    _VNode?.children[index]
      .querySelector('.content-box .comment-main .action-box')
      ?.insertAdjacentElement('afterend', createCommentVNode(_commentItem, _type));
  }
};
const handleDeleteComment = async (p: {
  commentId: number;
}) => {
  await ElMessageBox.confirm('是否删除评论？', '提示', {
    type: 'warning',
    showClose: false,
    draggable: true,
    showCancelButton: false,
    closeOnClickModal: false,
    cancelButtonText: '取消',
    confirmButtonText: '确定'
  });
  await deleteCommentItem(p);
  emits('sub-reply-success');
};
</script>

<template>
  <div
    ref="commentRef"
    class="comment-list cz-w-full"
  >
    <div
      v-for="(item, index) in dataComputed"
      :key="item"
      class="comment-item cz-flex"
    >
      <div class="popover-box user-popover cz-popover">
        <a class="user-link">
          <div class="avatar cz-avatar avatar">
            <img
              :key="item.userInfo.avatar"
              :alt="item.userInfo.username"
              :src="item.userInfo.avatar"
              class="lazy avatar-img"
              loading="lazy"
            >
          </div>
        </a>
      </div>
      <div class="content-box">
        <div class="comment-main">
          <div class="user-box">
            <div class="popover-box user-popover">
              <a class="username username">
                <span
                  class="name"
                  style="max-width: 128px;position: relative"
                >
                  {{ item.userInfo.username }}{{ (item.isPublisher === 1) ? '（我）' : "" }}
                </span>
              </a>
            </div>
            <time
              :datetime="item.createDate"
              :title="item.createDate"
              class="time"
            >
              {{ useBeforeDate(item.createDate) }}
            </time>
          </div>
          <div
            class="content"
            v-html="useEmojiTransform(item.content)"
          />
          <div class="action-box">
            <div class="action-left">
              <div class="item dig-item cz-flex">
                <cz-svg
                  class="cz-mr-1"
                  name="like"
                />
                点赞
              </div>
              <div
                v-if="item.isPublisher!==1"
                class="item flex"
                @click="handleClickComment(<HTMLDivElement>commentRef,index, 1, <ICommentList.SubCommentList>item)"
              >
                <cz-svg
                  class="cz-mr-1"
                  name="reply"
                />
                回复
              </div>
              <div
                v-if="item.isPublisher === 1"
                class="hidden item-delete cursor-pointer cz-text-[#f56C6C]"
                @click="handleDeleteComment({commentId: item.commentId})"
              >
                <cz-svg
                  class="cz-mr-1"
                  name="delete"
                />
                删除
              </div>
            </div>
          </div>
        </div>
        <div
          v-if="item.subComment.list.length > 0"
          class="sub-reply-wrapper"
        >
          <sub-reply
            :ref="(el)=>subCommentRefs[index]=el"
            :data="item.subComment"
            @on-delete-comment="()=> emits('sub-reply-success')"
            @on-click-comment="(ind, subCommentItem)=>
              handleClickComment(subCommentRefs[index].$el, ind, 2, subCommentItem)"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
@import "reply.scss";
</style>
